 
package com.wtzz.police.base.util;
/**  
*  
* @author zxh  
* @date 2018-10-31   
*/

import com.wtzz.police.base.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebTool {

	/**
	 * 获取当前用户
	 * @return
	 */
	public static final User getCurrentUser() {
		SecurityContext  sc = SecurityContextHolder.getContext();
		if(sc!=null && sc.getAuthentication()!=null && sc.getAuthentication().getPrincipal()!=null && sc.getAuthentication().getPrincipal() instanceof User) {
			return (User) sc.getAuthentication().getPrincipal();
		}
		return null;
	}

	public static final void setCurrentUser(User user) {
		SecurityContext  sc = SecurityContextHolder.getContext();
		if(sc!=null && sc.getAuthentication()!=null && sc.getAuthentication().getPrincipal()!=null && sc.getAuthentication().getPrincipal() instanceof User) {
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
			sc.setAuthentication(authentication);
		}
	}
	
	public static final HttpSession getSession() {
		HttpServletRequest req = getRequest();
		return req!=null?getRequest().getSession():null;
	}
	
	public static final HttpServletRequest getRequest() {
		ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return req!=null?req.getRequest():null;
	}
	
	public static final HttpServletResponse getResponse() {
		ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return req.getResponse();
	}
	
}
